﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NFine.Application;
using NFine.Application.InformationCenter;
using NFine.Code;
using NFine.Domain._02_ViewModel;
using NFine.Domain._03_Entity.InformationCenter;
using System.Text;
using System.IO;
using NFine.Domain._03_Entity.Biz;

namespace NFine.Web.Areas.InformationCenter.Controllers
{
    [HandlerLogin]
    public class MessagesController : ControllerBase
    {
        private SysMessagesApp messagesApp = new SysMessagesApp();
        private SysMessageReplyApp replyApp = new SysMessageReplyApp();
        private string moduleName = "留言模块";

        public override ActionResult Index()
        {
            var isAdmin = OperatorProvider.Provider.GetCurrent().IsSystem;
            ViewData["isAdmin"] = isAdmin;
            var model = messagesApp.GetBasicSetting();
            
            return View(model);
            //return base.Index();
        }


        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateInput(false)]
        public ActionResult SubmitFormBaseSetting(BasicSettingEntity entity, string old)
        {
            entity.F_Id = "ruibu";
            int result = messagesApp.SubmitFormBaseSetting(entity);
            if (result > 0)
            { 
                return Success("设置成功。");
            }
            else
                return Error("设置失败。");
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJson(Pagination pagination, bool isRead, string keyword)
        {
            var user = OperatorProvider.Provider.GetCurrent();
            var isAdmin = user.IsSystem;
            var userId = user.UserId;
            var data = new
            {
                rows = messagesApp.GetList(pagination, isRead, isAdmin, userId, keyword),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };
            return Content(data.ToJson());
        }

        [HttpGet]
        public override ActionResult Form()
        {
            var user = OperatorProvider.Provider.GetCurrent();
            ViewData["username"] = user.UserName;
            ViewData["userid"] = user.UserId;
            return View();
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateInput(false)]
        public ActionResult SubmitForm(SysMessagesEntity entity)
        {
            try
            {
                entity.F_CreatorTime = DateTime.Now;
                messagesApp.SubmitForm(entity, "");
                return Success("留言提交成功。");
            }
            catch (Exception ex)
            {
                addLog(moduleName, DbLogType.Create.ToString(), false, "留言提交失败，" + ex.Message);
                return Error("留言提交失败，服务器端发生错误。");
            }
        }

        [HttpGet]
        public ActionResult ViewReply(string keyValue)
        {
            View_Messages sysMessagesEntity = messagesApp.GetViewModel(keyValue);
            var user = OperatorProvider.Provider.GetCurrent();
            if (sysMessagesEntity.F_CreatorUserId != user.UserId)
            {
                // 如果不是本人发出的留言，则设为已读
                messagesApp.SetMessageIsRead(keyValue, true);
            }
            return View(sysMessagesEntity);
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult ReplyList(string messageId)
        {
            var list = replyApp.GetList(messageId);
            return Success(list.ToJson());
        }

        public ActionResult DoReply(SysMessagesReplyEntity replyEntity)
        {
            try
            {
                var user = OperatorProvider.Provider.GetCurrent();
                replyEntity.F_CreatorUserId = user.UserId;
                replyEntity.F_CreatorTime = DateTime.Now;
                replyApp.SubmitForm(replyEntity);
                // 将该条留言设置为未读，且更新人为当前回复用户
                var message = messagesApp.GetForm(replyEntity.F_MessageId);
                message.F_LastModifyUserId = user.UserId;
                message.F_IsRead = false;
                messagesApp.SubmitForm(message, message.F_Id);
                return Success("提交成功");
            }
            catch (Exception ex)
            {
                addLog(moduleName, DbLogType.Create.ToString(), false, "提交回复失败，" + ex.Message);
                return Error("提交失败");
            }
        }

        public ActionResult ggIndex()
        {
            var isAdmin = OperatorProvider.Provider.GetCurrent().IsSystem;
            ViewData["isAdmin"] = isAdmin;
            var model = messagesApp.GetBasicSetting();

            return View(model);
            //return base.Index();
        }

        #region 轮播图片
        public ActionResult NavigationIndex()
        {
            var entity = messagesApp.getImages();
            return View(entity);
        }
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitFormImage(NavigationImageEntity entity)
        {

            int result = messagesApp.saveImages(entity);
            if (result > 0)
            {
                return Success("设置成功。");
            }
            else
                return Error("设置失败。");
        }
        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="fileData"></param>
        /// <returns></returns>
        public ActionResult Upload(HttpPostedFileBase fileData)
        {
            string newFilePath = "";
            if (fileData != null)
            {
                //处理乱码
                ControllerContext.HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8");
                ControllerContext.HttpContext.Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
                ControllerContext.HttpContext.Response.Charset = "UTF-8";
                string uploadPath = Request.MapPath("~/UploadFiles/"+Request["folder"]+"/");

                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                string fileName = Path.GetFileName(fileData.FileName); //原始文件名称
                string fileExtension = Path.GetExtension(fileName); //文件扩展名
                string saveName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtension; //保存文件名称
                newFilePath = uploadPath + saveName;
                fileData.SaveAs(newFilePath);
                ControllerContext.HttpContext.Response.Write(saveName);
            }
            return Success("上传成功");
        }
        #endregion
    }
}